<?php
/**
 * Copyright (c) 2006-2008, Julien PORTALIER
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright    Copyright (c) 2006-2008, Julien PORTALIER
 * @link         http://featherphp.googlecode.com/
 * @license      http://www.opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * Translates an array to an XML string.
 */
function array_to_xml($arr, $tag)
{
	ob_start();
	
	if (is_array($arr) and isset($arr[0]))
	{
		# list of items
		$tag = Inflector::underscore($tag);
		foreach($arr as $v)
		{
			if (is_array($v))
			{
				echo "\n<$tag>";
				echo array_to_xml($v, $tag);
				echo "\n</$tag>";
			}
			else
			{
				echo "\n\t<$tag>".htmlspecialchars($v)."</$tag>";
			}
		}
	}
	elseif (is_array($arr) and !empty($arr))
	{
		# item
		foreach($arr as $k => $v)
		{
			$k = Inflector::underscore($k);
			if (is_array($v))
				echo (!empty($v)) ? array_to_xml($v, $k) : "\n\t<$k/>";
			else
			{
				echo (empty($v) and strlen($v) === 0) ? "\n\t<$k/>" :
					"\n\t<$k>".htmlspecialchars($v)."</$k>";
			}
		}
	}
	else
	{
		echo "<$tag/>\n";
	}
	
	return ob_get_clean();
}

/**
 * Translates an array to an XML string.
 * @param  array  $a
 * @return string $xml
 * @deprecated
 */
function array_to_xmlstring(array $a, $root='root')
{
	$str  = "<$root>";
	foreach($a as $d)
	{
		$str .= '<data';
		foreach($d as $k => $v)
		{
			$v = htmlspecialchars($v);
			$str .= " $k=\"$v\"";
		}
		$str .= '/>';
	}
	$str .= "</$root>";
	return $str;
}


?>